#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <time.h>
#include <strings.h>
#include "gauthenticate.h"
#include "gprinter.h"
#include <unistd.h>
#include <strophe.h>
#include <stdarg.h>
#include <unistd.h>
#include "logger.h"
#include <libconfig.h>

#define SOURCE  		"Armooo-PrintProxy-1"
#define PRINT_CLOUD_SERVICE_ID  "cloudprint"
#define CLIENT_LOGIN_URL 	"/accounts/ClientLogin"
#define PRINT_CLOUD_URL  	"/cloudprint/"

static char app_name[256] = ""; /* name of this app */
static char username[256], password[256];
static gservice* service;

void my_logger(void * const userdata, const xmpp_log_level_t level,
               const char * const area, const char * const msg)
{
    if (strcmp((char *)userdata, app_name) == 0 && level == XMPP_LEVEL_DEBUG) {
        clupsdLogMessage(CLUPSD_DEBUG, "%s\n", msg);
    }
}

int message_handler(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata)
{
	xmpp_ctx_t *ctx = (xmpp_ctx_t*)userdata;

	if(!xmpp_stanza_get_child_by_name(stanza, "push")) 
		return 1;
	if(!strcmp(xmpp_stanza_get_attribute(stanza, "from"), "cloudprint.google.com")) 
		return 1;

	return 1;
}

void conn_handler(xmpp_conn_t * const conn, const xmpp_conn_event_t status, 
		  const int error, xmpp_stream_error_t * const stream_error,
		  void * const userdata)
{
    xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;

    if (status == XMPP_CONN_CONNECT) {
	xmpp_stanza_t *subscribe, *item, *envelop;
	clupsdLogMessage(CLUPSD_NOTICE, "Connected and listening for print jobs from Google Cloud Print." );
	xmpp_handler_add(conn,message_handler, NULL, "message", NULL, ctx);

	const char *jid = xmpp_conn_get_jid(conn);
	const char *fjid = xmpp_conn_get_bound_jid(conn);
	envelop = xmpp_stanza_new(ctx);
	xmpp_stanza_set_name(envelop, "iq");
	xmpp_stanza_set_attribute(envelop, "from", fjid);
	xmpp_stanza_set_attribute(envelop, "to", jid);
	xmpp_stanza_set_attribute(envelop, "type", "set");
	xmpp_stanza_set_attribute(envelop, "id", "1");

	subscribe = xmpp_stanza_new(ctx);
	xmpp_stanza_set_name(subscribe, "subscribe");
	xmpp_stanza_set_attribute(subscribe, "xmlns", "google:push");
	xmpp_stanza_add_child(envelop, subscribe);

        item = xmpp_stanza_new(ctx);
	xmpp_stanza_set_name(item, "item");
	xmpp_stanza_set_attribute(item, "channel", "cloudprint.google.com");
	xmpp_stanza_set_attribute(item, "from", "cloudprint.google.com");
	xmpp_stanza_add_child(subscribe, item);
	xmpp_send(conn, envelop);
	xmpp_stanza_release(envelop);
    }
    else {
        char *dbg; size_t len;
        xmpp_stanza_to_text(stream_error->stanza, &dbg, &len);

	clupsdLogMessage(CLUPSD_ERROR, "Oops something went wrong - unable to connect. Check your user name and password for Google Cloud Print" );
	clupsdLogMessage(CLUPSD_ERROR, "Status: %d\nError Type: %d\nError: %s\nStanza: %s\n", status, stream_error->type, stream_error->text, dbg);
        free(dbg);
	xmpp_stop(ctx);
    }
}


int run_as_daemon(gservice *service) {
	pid_t pid, sid;
	int retval;
	xmpp_ctx_t	*xmpp_ctx;
 	xmpp_conn_t	*xmpp_con;
        xmpp_log_t	 xmpp_log;

	xmpp_log.handler = my_logger;
        xmpp_log.userdata = app_name;

	if (0) {
		/* fork the parent process */
		pid = fork();
		if (pid < 0) {
			exit(EXIT_FAILURE);
		}

		/* if the pid is good then we can exit the parent process. */
		if (pid > 0) {
			fprintf(stderr, "Running as a daemon\n");
			exit(EXIT_SUCCESS);
		}

		/* this is the daemon child process. */
		umask(0);

		/* avoid becomign an orphan */
		sid = setsid();
		if (sid < 0) {
			exit(EXIT_FAILURE);
		}

		/* chdir to safety */
		if((chdir("/")) < 0) {
			exit(EXIT_FAILURE);
		}

		close(STDIN_FILENO);
		close(STDOUT_FILENO);
		close(STDERR_FILENO);
 	}
	/* setup the log file. */
	logger_init();

	xmpp_initialize();
        xmpp_ctx = xmpp_ctx_new(NULL, &xmpp_log);
	xmpp_con = xmpp_conn_new(xmpp_ctx);

        if(!xmpp_con) {
		exit(1);
	}

	xmpp_conn_set_jid(xmpp_con, username);
	xmpp_conn_set_pass(xmpp_con, password);
	xmpp_conn_set_auth_token(xmpp_con, service->xmpp_auth);

	//connect to the server
	retval = xmpp_connect_client(xmpp_con, "talk.google.com", 0, 
						conn_handler, xmpp_ctx);

	xmpp_run(xmpp_ctx);

	xmpp_conn_release(xmpp_con);
	xmpp_ctx_free(xmpp_ctx);
        xmpp_shutdown();
	logger_close();
}

static int my_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp);
/* debug */
struct data {
  char trace_ascii; /* 1 or 0 */ 
};

gservice *svc_login(char *email, char* password) {
  gservice *cloudprint = gcal_construct(1);
  int res = gcal_get_authentication(cloudprint, email, password);
  printf("Auth: %s\n", cloudprint->auth);
  return cloudprint;
}

gservice *xmpp_login(char *email, char* password) {
 	gservice *xmpp_svc = gcal_construct(1);
	xmpp_svc->service = "mail";
	int res = gcal_get_authentication(xmpp_svc, email, password);
	printf("Auth: %s\n", xmpp_svc->auth);
	return xmpp_svc;
}

static clupsd_printer_t* register_printer(gservice *svc, char *name, char *file) {

 clupsd_printer_t *prn;

 /* if file is null, then see if we can find this printer on cups. */
 if(!file) {
	prn = find_cups_printer(name);
	PRINTER_SET(prn, proxy, svc->proxy);
 } else {
 	clupsd_printer_t *prn = clupsdNewPrinter(name);
	PRINTER_SET(prn, ppd, file);
	PRINTER_SET(prn, description, "No description");
	PRINTER_SET(prn, proxy, svc->proxy);
 }
 if (prn) {
	 int res = add_printer(svc, prn);
 }
 return prn;
}

static void print_usage(char* app) {
   fprintf(stderr, "%s: [-u username -p password] [-ld | -r printer_id | -n printer_name -f ppd_file]\n", app);
}

main(int argc, char** argv) {
   char option = 0;
   char *proxy = NULL;
   char *printer_file = NULL;
   struct data config = {0};
   char c;
   char *command = NULL;
   char *subject = NULL;

   strncpy(app_name, argv[0], sizeof(app_name));

   while((c = getopt(argc, argv, "h:u:p:df:s:")) != -1) {
	switch (c)
	{
		case 'u':
			strncpy(username, optarg, sizeof(username)); 
			username[sizeof(username)-1] = '\0';
			break;
		case 'p':
			strncpy(password, optarg, sizeof(password)); 
			password[sizeof(password)-1] = '\0';
			break;
		case 'd':
   			config.trace_ascii = 1; /* enable ascii tracing */ 
			break;
		case 'f':
			printer_file = optarg;
			break;
		case 's':
			proxy = optarg;
			break;
		default:
			option = 'h';
			break;
	}
   }

   //command follows last option
   if(optind < argc) {
	command = argv[optind];
	optind ++;
	if(optind < argc) 
	   subject = argv[optind];
   }

   //username and password set? then login..
    service = gcal_construct(0);
    FILE* f = fopen("./.cloudprint.auth", "r");
    if (f) {
	    char auth[1028];
	    fgets(auth, sizeof(auth), f); 
	    if(auth[strlen(auth)-1] == '\n') auth[strlen(auth)-1] = '\0';
	    strncpy(username, auth, sizeof(username)); 
	    fgets(auth, sizeof(auth), f);
	    if(auth[strlen(auth)-1] == '\n') auth[strlen(auth)-1] = '\0';
	    service->auth = strdup(auth);
	    fgets(auth, sizeof(auth), f);
	    if(auth[strlen(auth)-1] == '\n') auth[strlen(auth)-1] = '\0';
	    service->xmpp_auth = strdup(auth);
	    fclose(f);
    }

   if(proxy) {
	service->proxy = strdup(proxy);
   } else {
        service->proxy = NULL;
   }

   if( !service->auth || !service->xmpp_auth) {
	fprintf(stderr, "You are not logged into google cloudprint please login\n");
	print_usage(argv[0]);
	exit(1);
   }  

   if(config.trace_ascii) {
	fprintf(stderr, "Debugging is enabled\n");
	curl_easy_setopt(service->curl, CURLOPT_DEBUGFUNCTION, my_trace);
	curl_easy_setopt(service->curl, CURLOPT_DEBUGDATA, &config);
	curl_easy_setopt(service->curl, CURLOPT_VERBOSE, 1L);
   }

   if(command) {
	if(strncmp(command, "list-cloud", 9) == 0) {
		get_cloud_printers(service);
	} else if(strncmp(command, "list-cups", 9) == 0) {
		get_cups_printers(service);
	} else if(strncmp(command, "add", 3) == 0) {
		//printer name must follow
		if(subject != NULL && service->proxy != NULL) {
			register_printer(service, subject, printer_file);
		} else {
			fprintf(stderr, "usage: %s [-f driver-file] -s service-name add cups-printer-name\n", app_name);
		}
	} else if(strncmp(command, "run", 3) == 0) {
		if(service->proxy != NULL) {
			run_as_daemon(service);
		} else {
			fprintf(stderr, "usage: %s -s service-name run\n", app_name);
		}
	} else if(strncmp(command, "login", 5) == 0) {
		if(strlen(username) > 0 && strlen(password) > 0) {
			service = svc_login(username, password);
			gservice *xmpp = xmpp_login(username, password);
			FILE* f = fopen("./.cloudprint.auth", "w");
			fputs(username, f);
			fputs("\n", f);
			fputs(service->auth, f);
			fputs("\n", f);
			fputs(xmpp->auth, f);
			fclose(f);
		} else {
			fprintf(stderr, "usage: %s -u username -p password login\n", app_name);
		}
	} else if(strncmp(command, "del", 3) == 0) {
		if(subject != NULL) {
			delete_printer(service, subject);
		} else {
			fprintf(stderr, "usage: %s del google-cloud-printer-id\n", app_name);
		}
	} else {
	 fprintf(stderr, "Unknown command [%s] specified\n", command); print_usage(argv[0]);
	}
  } else {
	fprintf(stderr, "No command specified\n", command); print_usage(argv[0]);
  }
}

 
static
void dump(const char *text,
          FILE *stream, unsigned char *ptr, size_t size,
          char nohex)
{
  size_t i;
  size_t c;
 
  unsigned int width=0x10;
 
  if(nohex)
    /* without the hex output, we can fit more on screen */ 
    width = 0x40;
 
  fprintf(stream, "%s, %10.10ld bytes (0x%8.8lx)\n",
          text, (long)size, (long)size);
 
  for(i=0; i<size; i+= width) {
 
    fprintf(stream, "%4.4lx: ", (long)i);
 
    if(!nohex) {
      /* hex not disabled, show it */ 
      for(c = 0; c < width; c++)
        if(i+c < size)
          fprintf(stream, "%02x ", ptr[i+c]);
        else
          fputs("   ", stream);
    }
 
    for(c = 0; (c < width) && (i+c < size); c++) {
      /* check for 0D0A; if found, skip past and start a new line of output */ 
      if (nohex && (i+c+1 < size) && ptr[i+c]==0x0D && ptr[i+c+1]==0x0A) {
        i+=(c+2-width);
        break;
      }
      fprintf(stream, "%c",
              (ptr[i+c]>=0x20) && (ptr[i+c]<0x80)?ptr[i+c]:'.');
      /* check again for 0D0A, to avoid an extra \n if it's at width */ 
      if (nohex && (i+c+2 < size) && ptr[i+c+1]==0x0D && ptr[i+c+2]==0x0A) {
        i+=(c+3-width);
        break;
      }
    }
    fputc('\n', stream); /* newline */ 
  }
  fflush(stream);
}
 
static
int my_trace(CURL *handle, curl_infotype type,
             char *data, size_t size,
             void *userp)
{
  struct data *config = (struct data *)userp;
  const char *text;
  (void)handle; /* prevent compiler warning */ 
 
  switch (type) {
  case CURLINFO_TEXT:
    fprintf(stderr, "== Info: %s", data);
  default: /* in case a new one is introduced to shock us */ 
    return 0;
 
  case CURLINFO_HEADER_OUT:
    text = "=> Send header";
    break;
  case CURLINFO_DATA_OUT:
    text = "=> Send data";
    break;
  case CURLINFO_SSL_DATA_OUT:
    text = "=> Send SSL data";
    break;
  case CURLINFO_HEADER_IN:
    text = "<= Recv header";
    break;
  case CURLINFO_DATA_IN:
    text = "<= Recv data";
    break;
  case CURLINFO_SSL_DATA_IN:
    text = "<= Recv SSL data";
    break;
  }
 
  dump(text, stderr, (unsigned char *)data, size, config->trace_ascii);
  return 0;
}
 
